package com.yokead.shield;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.CharsetUtil;
import cn.jiangzeyin.StringUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yokead.common.Config;

import java.io.File;
import java.io.IOException;

/**
 * Created by jiangzeyin on 2017/9/7.
 */
public class ShieldUtil {
    public static String getShieldConfPath() {
        return Config.Shield.getShieldPath();
    }

    /**
     * 获取所有屏蔽信息
     *
     * @return
     * @throws IOException
     */
    public static JSONArray getJsonArray() throws IOException {
        File file = new File(getShieldConfPath(), "info.conf");
        String json = FileUtil.readString(file, CharsetUtil.UTF_8);
        if (StringUtil.isEmpty(json)) {
            return new JSONArray();
        }
        return (JSONArray) JSONArray.parse(json);
    }


    public static JSONObject getObj(String url) throws IOException {
        JSONArray jsonArray = getJsonArray();
        for (Object aJsonArray : jsonArray) {
            JSONObject jsonObject = (JSONObject) aJsonArray;
            String oUrl = jsonObject.getString("url");
            if (url.equals(oUrl)) {
                return jsonObject;
            }
        }
        return null;
    }

    public static JSONObject getObjById(String id) throws IOException {
        JSONArray jsonArray = getJsonArray();
        for (Object aJsonArray : jsonArray) {
            JSONObject jsonObject = (JSONObject) aJsonArray;
            String oId = jsonObject.getString("id");
            if (oId.equals(id)) {
                return jsonObject;
            }
        }
        return null;
    }
}
